<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\Pay\RmsPayEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Library\Rms\RmsUserApi;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftOutfitMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\OpenShop\ShopEngineeringConstruction\OpenShopEngineeringConstructionModel;
use App\Remote\Orm\OrmShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\OpenShop\Feishu\DesignerEquipmentService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\ShopCheckAcceptService;
use App\Service\OpenShop\Feishu\ShopEngineeringConstructionService;
use App\Service\OpenShop\Feishu\SpaceDesignService;
use App\Service\OpenShop\Feishu\StartBusinessService;
use App\Service\OpenShop\Feishu\UserExtContractService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Service\OpenShop\Merchant\SiteMissionService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\OpenShop\Wap\SignOrderService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;

class SkipStep extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:skip-step';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '跳过阶段';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();


        $this->param = (object)[
            'orderNo' => 'KD2022100847376592',
        ];
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    private object $param;

    public function handle()
    {
        Config::set('event.connection', 'sync');
        HistoryOrderParam::$importOrderMode = true;
        $this->param->name                  = OpenShopUserIdentityCardModel::query()->where('orderNo', $this->param->orderNo)
                                                                           ->value('name') ?? '';

        $this->do();
    }

    private function do()
    {
        $this->designPay();
    }

    private function setRmsUserInfoByAuth(?array $userInfo)
    {
        request()->replace(['userInfo' => (object)$userInfo]);
    }


    private function equipmentPay()
    {
        $equipmentPrice = 0;
        $bizId = 'D91960826524696576';


        $payPrice = bcmul($equipmentPrice, 100);
        $payNo    = '';

        $sysType    = CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT;
        $payChannel = OpenShopSignOrderPayHistoryModel::PAY_CHANNEL_OFFLINE;

        $addPayLogId = (new SignOrderService($this->param->orderNo, null, false))
            ->internalPaySuccess($bizId, $payPrice, $payChannel, $payNo, $sysType);

        // 金额为0时，事后软删除支付流水
        if ($payPrice <= 0) {
            OpenShopSignOrderPayHistoryModel::deleteData($addPayLogId);
        }
    }

    private function designPay()
    {
        $sysType = CheckEnum::SYS_TYPE_OPEN_SHOP_DESIGN;

        $design = OpenShopSpaceDesignCostMappingModel::query()
                                                     ->where('orderNo', $this->param->orderNo)
                                                     ->whereIn('orderStatus', [
                                                         OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_0,
                                                         OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_1
                                                     ])
                                                     ->first();
        $pay = $design->totalFee - $design->payFee;

        // 备注: 姓名 + 加盟费
        $subject = $this->param->name . '-' . RmsPayEnum::SYS_TYPE_TEXT[$sysType].'（历史补录）';

        // 新增一条支付流水
        $addPayLogId = OpenShopSignOrderPayHistoryModel::addHistory(
            $this->param->orderNo,
            $pay,
            $pay,
            OpenShopSignOrderPayHistoryModel::PAY_CHANNEL_OFFLINE,
            OpenShopSignOrderPayHistoryModel::TYPE_FINAL,
            $subject,
            $sysType,
            $design->preparationNo
        );

        // 强制手动支付成功
        (new SignOrderService($this->param->orderNo))->paySuccess($addPayLogId, $pay);

        // 金额为0时，事后软删除支付流水
        if ($pay <= 0) {
            OpenShopSignOrderPayHistoryModel::deleteData($addPayLogId);
        }
    }

    private function softPay()
    {
        $sysType = CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE;

        // 备注: 姓名 + 加盟费
        $subject = $this->param->name . '-' . RmsPayEnum::SYS_TYPE_TEXT[$sysType].'（历史补录）';

        $decorate = OpenShopSpaceDesignSoftOutfitMappingModel::query()->where('orderNo', $this->param->orderNo)
            ->whereIn('orderStatus', [
                OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_0,
                OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_1
            ])
                                                             ->first();

        $payPrice = $decorate->fee;
        $bizId    = $decorate->preparationNo;

        // 新增一条支付流水
        $addPayLogId = OpenShopSignOrderPayHistoryModel::addHistory(
            $this->param->orderNo,
            $payPrice,
            $payPrice,
            OpenShopSignOrderPayHistoryModel::PAY_CHANNEL_OFFLINE,
            OpenShopSignOrderPayHistoryModel::TYPE_FINAL,
            $subject,
            $sysType,
            $bizId
        );

        // 强制手动支付成功
        (new SignOrderService($this->param->orderNo))->paySuccess($addPayLogId, $payPrice);

        // 金额为0时，事后软删除支付流水
        if ($payPrice <= 0) {
            OpenShopSignOrderPayHistoryModel::deleteData($addPayLogId);
        }
    }

    private function leaguePay()
    {
        $signOrder = OpenShopSignOrderModel::query()->where('orderNo', $this->param->orderNo)->first();

        // 阶段不对
        if ($signOrder->step != SignOrderEnum::STEP_2) {
            throw new \Exception("orderNo:{$this->param->orderNo} step:{$signOrder->step} 阶段异常");
        }

        if ($signOrder->contractRel->shopCount != 1) {
            throw new \Exception("orderNo:{$this->param->orderNo} shopCount:{$signOrder->contractRel->shopCount} 店铺数量错");
        }

        $signOrder->orderType = SignOrderEnum::ORDER_TYPE_IMPORT;
        $signOrder->save();

        // 支付
        OrderService::submitOrderProof((object)[], $this->param->orderNo,
            ['proof' => [['price' => $signOrder->shouldPayPrice, 'img' => '']]]);

        $shopId = OpenShopMainProcessModel::query()
                                          ->where('orderNo', $this->param->orderNo)
                                          ->value('shopId');
        if (!$shopId) {
            throw new \Exception('shopId为空');
        }

        // 金额为0时，事后软删除支付流水
        if ($signOrder->shouldPayprice <= 0) {
            $payId = OpenShopSignOrderPayHistoryModel::query()
                                                     ->where('orderNo', $this->param->orderNo)
                                                     ->where('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_LEAGUE)
                                                     ->where('payStatus',
                                                         OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                                     ->orderByDesc('id')
                                                     ->value('id');

            OpenShopSignOrderPayHistoryModel::deleteData($payId);
        }
    }


}
